<?php

include_once "src/rrsexception/DBConnectionException.php";
include_once "src/rrsexception/DBException.php";

/**
 * It represents the connection settings of our application.
 *
 * @author fcanache
 */
class DBConnection {

    const DB_SERVER_ADDRESS = "your_db_server_address";
    const DB_LOGIN = "your_login";
    const DB_PASSWORD = "your_password";
    const DB_NAME = "rrsdb";

    private $connectionId;

    /**
     * Constructor. It creates the connection to the database server and
     *              opens a connection with the specified database.
     *
     * @exception   If when opening the connection with the database an error
     *              is detected an exception (DBConnectionException) is thrown.
     * @exception   If when selecting the database specified an error
     *              is detected an exception (DBException) is thrown.
     */
    function __construct () {
        $this->connectionId = mysql_connect(self::DB_SERVER_ADDRESS, self::DB_LOGIN, self::DB_PASSWORD);
        if(!$this->connectionId) {
            throw new DBConnectionException("Unable to establish connection with the database server.");
        }
        if(!mysql_select_db(self::DB_NAME, $this->connectionId)) {
            throw new DBException("Unable to select the specified database.");
        }
    }

    /**
     * Destructor of the DBConnection class.
     */
    function __destruct () {

    }

    /**
     * Terminates the database connection associated to the connection link.
     */
    function disconnect () {
        mysql_close($this->connectionId);
    }

    /**
     * Executes a SQL statement.
     *
     * @param $query   A SQL statement.
     * @return         For SELECT and other statements returning resultset,
     *                 it returns a resource. For other type of SQL statements,
     *                 INSERT, UPDATE, and DELETE, it returns TRUE.
     * @exception      If an error is detected during the execution of the SQL
     *                 statement an exception (DBException) is thrown.
     */
    function execute ($query) {
        $result = mysql_query($query, $this->connectionId);
        if(!$result) {
            throw new DBException("Query execution failed.<br />Query Statement: " . $query);
        }
        return $result;
    }

   function escapeString($myString) {
      if(!is_null($myString)){
       if (get_magic_quotes_gpc())
           stripslashes($myString);
       if (!is_numeric($myString))
           $myString = mysql_real_escape_string($myString, $this->connectionId);
      }
      else $myString='NULL';
      return $myString;
   }
}
?>
